package mybatis.test;

import mybatis.dao.StudentDao;
import mybatis.pojo.Student;
import mybatis.util.MybatisUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @Author 汤舒青
 * @Version 1.0
 */


public class TestStudent {
    public static void main(String[] args) {
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
            //SQLsession ==Connection
            SqlSession sqlSession = build.openSession();
            //>>>Connection connection = sqlSession.getConnection();
            StudentDao mapper = sqlSession.getMapper(StudentDao.class);
            System.out.println(mapper.getClass().getName());
            System.out.println(Arrays.toString(mapper.getClass().getInterfaces()));
            List<Student> all = mapper.findALL();
            all.forEach(System.out::println);
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查
     */
    @Test
    public void findAll(){
        SqlSession s = MybatisUtil.get(true);
        StudentDao mapper = s.getMapper(StudentDao.class);
        List<Student> list = mapper.findALL();
        list.forEach(System.out::println);
        MybatisUtil.close(s);
    }
    /**
     * 增
     */
@Test
    public void addStudent(){
        SqlSession s = MybatisUtil.get();
        StudentDao mapper = s.getMapper(StudentDao.class);
        Student student = new Student("泽丽", "女", "113333252", "589662", "55465", 5, "2022-06-06", "合肥", "2019-04-15", "安庆", "123456", "3402020");
        int add = mapper.add(student);
        s.commit();
        System.out.println(add==1?"增加成功":"增加失败");
        MybatisUtil.close(s);
    }
    @Test
    public void findLimit(){
        SqlSession s = MybatisUtil.get();
        StudentDao mapper = s.getMapper(StudentDao.class);
        List<Student> list = mapper.findAllLimit(3, 10);
        list.forEach(System.out::println);
        MybatisUtil.close(s);
    }
    /**
     * 删
     */
    @Test
    public void deleteStu(){
        SqlSession s = MybatisUtil.get();
        StudentDao mapper = s.getMapper(StudentDao.class);
        int i = mapper.delete(2);
        s.commit();
        System.out.println(i==1?"删除成功":"删除失败");
        MybatisUtil.close(s);
    }
}
